package jp.bgbt.fles.app.bluetooth;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

import java.util.Iterator;

import jp.bgbt.fles.app.MainApplication;


public class BleServiceManager {

    private BleService bluetoothService;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            bluetoothService = ((BleService.LocalBinder) service).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            bluetoothService = null;
        }
    };

    private static class BleSingleton {
        static BleServiceManager instance = new BleServiceManager();
    }

    public static BleServiceManager getInstance() {
        return BleSingleton.instance;
    }

    private void initBlueService() {
//        if (isAppProcess()) {
            Intent intent = new Intent(MainApplication.getInstance(), BleService.class);
            MainApplication.getInstance().bindService(intent, connection, Context.BIND_AUTO_CREATE);
//        }
    }

    public BleService getBluetoothService() {
        if (bluetoothService == null)
            initBlueService();
        return bluetoothService;
    }

    /**
     * 判断该进程是否是app进程
     *
     * @return
     */
    private boolean isAppProcess() {
        String processName = getProcessName();
        if (processName == null || !processName.equalsIgnoreCase(MainApplication.getInstance().getPackageName())) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 获取运行该方法的进程的进程名
     *
     * @return 进程名称
     */
    private String getProcessName() {
        int processId = android.os.Process.myPid();
        String processName = null;
        ActivityManager manager = (ActivityManager) MainApplication.getInstance().getSystemService(Context.ACTIVITY_SERVICE);
        Iterator iterator = manager.getRunningAppProcesses().iterator();
        while (iterator.hasNext()) {
            ActivityManager.RunningAppProcessInfo processInfo = (ActivityManager.RunningAppProcessInfo) (iterator.next());
            try {
                if (processInfo.pid == processId) {
                    processName = processInfo.processName;
                    return processName;
                }
            } catch (Exception e) {
//                LogD(e.getMessage())
            }
        }
        return processName;
    }
}
